package com.warm.core.utils;

import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.warm.core.exception.JsonException;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

/**
 * json转换工具类
 *
 * @author warm
 */
@Slf4j
public class JsonUtil<T> {

    static final ObjectMapper mapper = new ObjectMapper();

    /**
     * 把Object转json字符串
     *
     * @param obj
     * @return
     */
    public static String objectToJson(Object obj) {
        try {
            return mapper.writeValueAsString(obj);
        } catch (Exception e) {
            log.error("把Object转json字符串失败！", e);
            throw new JsonException("把Object转json字符串失败！", e);
        }
    }

    /**
     * json字符串转换为对象
     *
     * @param json
     * @param obj
     * @return
     */
    public static <T> T jsonToObject(String json, Class<T> obj) {
        try {
            return mapper.readValue(json, obj);
        } catch (Exception e) {
            log.error("json字符串转换为对象！", e);
            throw new JsonException("json字符串转换为对象！", e);
        }
    }

    /**
     * json字符串转换为list对象
     *
     * @param json
     * @param obj
     * @return
     */
    public static <T> List<T> jsonToList(String json, Class<T> obj) {
        try {
            JavaType javaType = mapper.getTypeFactory().constructParametricType(List.class, obj);
            return mapper.readValue(json, javaType);
        } catch (Exception e) {
            log.error("json字符串转换为list对象！", e);
            throw new JsonException("json字符串转换为list对象！", e);
        }
    }

}